package com.api.qfengx.config.sql;

import com.alibaba.fastjson.JSON;
import com.weaver.qfengx.DaoUtils;
import com.weaver.qfengx.LogUtils;
import com.weaver.qfengx.StringUtils;
import com.weaver.qfengx.config.DevModeConfig;
import com.weaver.qfengx.entity.Result;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author Qfengx <qffg1998@126.com>
 * @Date 2021-07-06 17:25:05
 */
@Path("/qfengx/config/sql")
public class SqlExecApi {

    private static final LogUtils log = new LogUtils(SqlExecApi.class);

    @GET
    @Path("/exec")
    @Produces(MediaType.APPLICATION_JSON)
    public String exec(@Context HttpServletRequest request,
                       @Context HttpServletResponse response) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            if (user.getUID() != 1) {
                return JSON.toJSONString(Result.noPermission());
            }
            String name = request.getParameter("name");
            if (StringUtils.isEmpty(name)) {
                return JSON.toJSONString(Result.paramErr());
            }
            String sql = DevModeConfig.getPropConfig("sql.exec." + name, "").getValue();
            if (StringUtils.isEmpty(sql)) {
                return JSON.toJSONString(Result.fail("sql is empty"));
            }
            log.writeLog("sql exec => " + sql);
            List<Map<String, String>> mapList = DaoUtils.executeQueryToMapList(sql);
            log.writeLog("map list size => " + mapList.size());
            return JSON.toJSONString(Result.ok(mapList));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.exception().setMsg(e.getMessage()));
        }
    }

}
